package com.alex;

import static com.anythink.core.api.ATInitMediation.getStringFromMap;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.core.api.MediationInitCallback;
import com.anythink.rewardvideo.unitgroup.api.CustomRewardVideoAdapter;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;

import java.util.Map;

public class AlexGromoreRewardedVideoAdapter extends CustomRewardVideoAdapter {

    private final String TAG = getClass().getSimpleName();
    boolean isC2SBidding = false;
    String slotId;
    AlexGromoreConfig mATConfig;
    private Map<String, Object> mNetworkMap;

    private TTRewardVideoAd mTTRewardVideoAd;
    private boolean mHasCallbackReward;

    @Override
    public void loadCustomNetworkAd(final Context context, Map<String, Object> serverExtra,
                                    Map<String, Object> localExtra) {
        if (!(context instanceof Activity)) {
            notifyATLoadFail("", "Gromore: context must be activity");
            return;
        }
        if (!initAndVerifyRequestParams(context, serverExtra, localExtra)) {
            notifyATLoadFail("", "app_id or slot_id is empty!");
            return;
        }

        AlexGromoreInitManager.getInstance()
                .initSDK(context, serverExtra, new MediationInitCallback() {
                    @Override
                    public void onSuccess() {

                        MediationAdSlot.Builder mediationAdSoltBuilder = new MediationAdSlot.Builder();
                        if (mATConfig.adSound >= 0) {
                            mediationAdSoltBuilder.setMuted(mATConfig.adSound == 0);//是否静音
                        }
                        if (!TextUtils.isEmpty(mATConfig.mRewardName)) {
                            mediationAdSoltBuilder.setRewardName(mATConfig.mRewardName);
                        }
                        if (mATConfig.mRewardAmount >= 0) {
                            mediationAdSoltBuilder.setRewardAmount(mATConfig.mRewardAmount);
                        }

                        //start load rv
                        AdSlot.Builder adSlotBuilder = new AdSlot.Builder().setCodeId(slotId)
                                .setMediationAdSlot(mediationAdSoltBuilder.build());

                        if (!TextUtils.isEmpty(mATConfig.mUserId)) {
                            adSlotBuilder.setUserID(mATConfig.mUserId);
                        }
                        if (!TextUtils.isEmpty(mATConfig.mUserData)) {
                            adSlotBuilder.setUserData(mATConfig.mUserData);
                        }

                        AdSlot adSlot = adSlotBuilder.build();

                        TTAdNative adNativeLoader = TTAdSdk.getAdManager()
                                .createAdNative((Activity) context);//必须传入Activity才会有加载回调

                        adNativeLoader.loadRewardVideoAd(adSlot,
                                new TTAdNative.RewardVideoAdListener() {
                                    @Override
                                    public void onError(int errorCode, String errorMsg) {
                                        notifyATLoadFail("" + errorCode, errorMsg);
                                    }

                                    @Override
                                    public void onRewardVideoAdLoad(
                                            TTRewardVideoAd ttRewardVideoAd) {
                                    }

                                    @Override
                                    public void onRewardVideoCached() {
                                    }

                                    @Override
                                    public void onRewardVideoCached(
                                            TTRewardVideoAd ttRewardVideoAd) {
                                        mTTRewardVideoAd = ttRewardVideoAd;
                                        if (isC2SBidding) {
                                            runOnNetworkRequestThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    double price = 0;
                                                    try {
                                                        price = Double.parseDouble(
                                                                mTTRewardVideoAd.getMediationManager()
                                                                        .getBestEcpm()
                                                                        .getEcpm());//return cent
                                                        price = price / 100;//cast to yuan
                                                    } catch (Throwable t) {

                                                    }
                                                    if (price <= 0) {
                                                        price = AlexGromoreUtil.getBestPriceInCacheNew(
                                                                mTTRewardVideoAd);
                                                    }

                                                    mBiddingListener.onC2SBiddingResultWithCache(
                                                            ATBiddingResult.success(price,
                                                                    System.currentTimeMillis() + "",
                                                                    null, mATConfig.mCurrency),
                                                            null);
                                                }
                                            });
                                        } else {
                                            if (mLoadListener != null) {
                                                mLoadListener.onAdCacheLoaded();
                                            }
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        notifyATLoadFail("", errorMsg);
                    }
                });
    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra,
                                       Map<String, Object> localExtra,
                                       ATBiddingListener biddingListener) {
        isC2SBidding = true;
        loadCustomNetworkAd(context, serverExtra, localExtra);
        return true;
    }

    @Override
    public void show(Activity activity) {
        if (isAdReady()) {
            /** 5、设置展示监听器，展示广告 */
            mTTRewardVideoAd.setRewardAdInteractionListener(
                    new TTRewardVideoAd.RewardAdInteractionListener() {
                        @Override
                        public void onAdShow() {
                            mHasCallbackReward = false;
                            mNetworkMap = AlexGromoreConst.getNetworkMap(mTTRewardVideoAd);
                            if (mImpressionListener != null) {
                                mImpressionListener.onRewardedVideoAdPlayStart();
                            }
                        }

                        @Override
                        public void onAdVideoBarClick() {
                            if (mImpressionListener != null) {
                                mImpressionListener.onRewardedVideoAdPlayClicked();
                            }
                        }

                        @Override
                        public void onAdClose() {
                            if (mImpressionListener != null) {
                                mImpressionListener.onRewardedVideoAdClosed();
                            }
                        }

                        @Override
                        public void onVideoComplete() {
                            if (mImpressionListener != null) {
                                mImpressionListener.onRewardedVideoAdPlayEnd();
                            }
                        }

                        @Override
                        public void onVideoError() {
                            if (mImpressionListener != null) {
                                mImpressionListener.onRewardedVideoAdPlayFailed("",
                                        "Gromore: RV show fail");
                            }
                        }

                        @Override
                        public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                        }

                        @Override
                        public void onRewardArrived(boolean rewardVerify, int i, Bundle bundle) {
                            Log.i(TAG, "onRewardArrived(), rewardVerify: " + rewardVerify);
                            if (mImpressionListener != null && rewardVerify && !mHasCallbackReward) {
                                mImpressionListener.onReward();
                            }
                        }

                        @Override
                        public void onSkippedVideo() {

                        }
                    });
            mTTRewardVideoAd.setRewardPlayAgainInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                @Override
                public void onAdShow() {
                    mHasCallbackReward = false;
                    mNetworkMap = AlexGromoreConst.getNetworkMap(mTTRewardVideoAd);

                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdAgainPlayStart();
                    }
                }

                @Override
                public void onAdVideoBarClick() {
                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdAgainPlayClicked();
                    }
                }

                @Override
                public void onAdClose() {

                }

                @Override
                public void onVideoComplete() {
                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdAgainPlayEnd();
                    }
                }

                @Override
                public void onVideoError() {
                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdAgainPlayFailed("", "Again AD, Callback VideoError");
                    }
                }

                @Override
                public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int errorCode, String errorMsg) {

                }

                @Override
                public void onRewardArrived(boolean rewardVerify, int i, Bundle bundle) {
                    Log.i(TAG, "Again AD, onRewardArrived(), rewardVerify: " + rewardVerify);
                    if (mImpressionListener != null && rewardVerify && !mHasCallbackReward) {
                        mHasCallbackReward = true;
                        mImpressionListener.onAgainReward();
                    }
                }

                @Override
                public void onSkippedVideo() {
                }
            });
            mTTRewardVideoAd.showRewardVideoAd(activity);
        }
    }

    private boolean initAndVerifyRequestParams(Context context, Map<String, Object> serverExtra,
                                               Map<String, Object> localExtra) {
        String appId = getStringFromMap(serverExtra, "app_id");
        slotId = getStringFromMap(serverExtra, "slot_id");

        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(slotId)) {
            return false;
        }


        mATConfig = new AlexGromoreConfig(context, serverExtra);
        mATConfig.parseRewardLocalData(localExtra);

        return true;
    }

    @Override
    public void destory() {
        if (mTTRewardVideoAd != null && mTTRewardVideoAd.getMediationManager() != null) {
            mTTRewardVideoAd.getMediationManager().destroy();
        }
    }


    @Override
    public String getNetworkPlacementId() {
        return slotId;
    }

    @Override
    public String getNetworkSDKVersion() {
        return AlexGromoreInitManager.getInstance().getNetworkVersion();
    }

    @Override
    public String getNetworkName() {
        return AlexGromoreInitManager.getInstance().getNetworkName();
    }

    @Override
    public boolean isAdReady() {
        return mTTRewardVideoAd != null && mTTRewardVideoAd.getMediationManager().isReady();
    }

    @Override
    public Map<String, Object> getNetworkInfoMap() {
        return mNetworkMap;
    }
}
